import { CallHandler, ExecutionContext, NestInterceptor, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Logger } from '@/common/log4js/log4j.util';

/*
 统一记录接口的请求详情和响应数据
 */
@Injectable()
export class TransformInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {

        //请求拦截
        const request = context.switchToHttp().getRequest();
        const handler = context.getHandler(); // 获取路由处理函数（如 login 方法）
        //响应拦截
        return next.handle().pipe(map(data => {
            const logFormat = `
            -----------------------------------------------------------------------
            Request original url: ${request.originalUrl}
            Method: ${request.method}
            IP: ${request.ip}
            User: ${JSON.stringify(request.user)}
            PanCode: ${JSON.stringify(request.panCode)}
            Response data: ${JSON.stringify(data?.data || data)}
            -----------------------------------------------------------------------`;
            Logger.info(logFormat);
            Logger.access(logFormat);
            return data;
        }));
    }
}
